'use client';

import React, { useState } from 'react';
import { ContentInput } from '@/components/ContentInput';
import { PlatformSelector } from '@/components/PlatformSelector';
import { ContentResults } from '@/components/ContentResults';
import { GeneratedContent, ContentGenerationRequest } from '@/types';
import { PLATFORMS } from '@/constants/platforms';
import { SparklesIcon } from '@heroicons/react/24/outline';

export default function Home() {
  const [originalContent, setOriginalContent] = useState('');
  const [selectedPlatforms, setSelectedPlatforms] = useState<string[]>([]);
  const [generatedResults, setGeneratedResults] = useState<GeneratedContent[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handlePlatformToggle = (platformId: string) => {
    setSelectedPlatforms(prev => 
      prev.includes(platformId)
        ? prev.filter(id => id !== platformId)
        : [...prev, platformId]
    );
  };

  const handleSelectAll = () => {
    setSelectedPlatforms(PLATFORMS.map(p => p.id));
  };

  const handleClearAll = () => {
    setSelectedPlatforms([]);
  };

  const handleGenerate = async () => {
    if (!originalContent.trim()) {
      setError('请输入原始内容');
      return;
    }

    if (selectedPlatforms.length === 0) {
      setError('请至少选择一个平台');
      return;
    }

    setError(null);
    setIsGenerating(true);
    setGeneratedResults([]);

    try {
      const request: ContentGenerationRequest = {
        originalContent: originalContent.trim(),
        selectedPlatforms
      };

      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      });

      if (!response.ok) {
        throw new Error(`生成失败: ${response.statusText}`);
      }

      const data = await response.json();
      setGeneratedResults(data.generatedContents || []);
    } catch (error) {
      console.error('生成内容时出错:', error);
      setError(error instanceof Error ? error.message : '生成失败，请重试');
    } finally {
      setIsGenerating(false);
    }
  };

  const canGenerate = originalContent.trim().length > 0 && 
                     selectedPlatforms.length > 0 && 
                     !isGenerating;

  return (
    <div className="container mx-auto px-4 py-8 max-w-7xl">
      {/* 页面介绍 */}
      <div className="text-center mb-8">
        <h2 className="text-3xl font-bold mb-4">一键生成多平台文案</h2>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto">
          输入您的原始内容，选择目标平台，我们的AI将为每个平台生成专属的吸引人文案
        </p>
      </div>

      <div className="grid lg:grid-cols-2 gap-8">
        {/* 左侧：输入和设置 */}
        <div className="space-y-8">
          {/* 内容输入 */}
          <ContentInput
            content={originalContent}
            onContentChange={setOriginalContent}
          />

          {/* 平台选择 */}
          <PlatformSelector
            selectedPlatforms={selectedPlatforms}
            onPlatformToggle={handlePlatformToggle}
            onSelectAll={handleSelectAll}
            onClearAll={handleClearAll}
          />

          {/* 生成按钮 */}
          <div className="space-y-4">
            <button
              onClick={handleGenerate}
              disabled={!canGenerate}
              className="generate-button w-full flex items-center justify-center gap-3"
            >
              {isGenerating ? (
                <>
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full loading-spinner"></div>
                  <span>正在生成中...</span>
                </>
              ) : (
                <>
                  <SparklesIcon className="w-5 h-5" />
                  <span>开始生成文案</span>
                </>
              )}
            </button>

            {error && (
              <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
                {error}
              </div>
            )}

            {/* 使用提示 */}
            {!isGenerating && generatedResults.length === 0 && (
              <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg text-blue-600 text-sm">
                <h4 className="font-medium mb-2">💡 使用提示：</h4>
                <ul className="space-y-1 text-xs">
                  <li>• 输入内容越详细，生成的文案质量越高</li>
                  <li>• 不同平台会生成不同风格的内容</li>
                  <li>• 可以多次生成，选择最满意的版本</li>
                  <li>• 支持一键复制单个字段或完整内容</li>
                </ul>
              </div>
            )}
          </div>
        </div>

        {/* 右侧：生成结果 */}
        <div className="lg:sticky lg:top-24 lg:h-fit">
          <ContentResults 
            results={generatedResults} 
            isLoading={isGenerating}
          />
        </div>
      </div>

      {/* 特性介绍 */}
      {generatedResults.length === 0 && !isGenerating && (
        <div className="mt-16 grid md:grid-cols-3 gap-6">
          <div className="text-center p-6">
            <div className="text-3xl mb-4">🎯</div>
            <h3 className="font-semibold mb-2">精准定位</h3>
            <p className="text-sm text-muted-foreground">
              针对不同平台的用户特点和内容偏好，生成个性化文案
            </p>
          </div>
          
          <div className="text-center p-6">
            <div className="text-3xl mb-4">⚡</div>
            <h3 className="font-semibold mb-2">快速生成</h3>
            <p className="text-sm text-muted-foreground">
              AI驱动的内容生成，几秒钟内完成多平台文案创作
            </p>
          </div>
          
          <div className="text-center p-6">
            <div className="text-3xl mb-4">📋</div>
            <h3 className="font-semibold mb-2">一键复制</h3>
            <p className="text-sm text-muted-foreground">
              支持分别复制标题、正文、标签，或一键复制完整内容
            </p>
          </div>
        </div>
      )}
    </div>
  );
}